package com.e2e.haiti.infrastructure.surveyor;

import java.util.zip.Inflater;

import com.actionbarsherlock.app.SherlockFragment;
import com.e2e.haiti.infrastructure.surveyor.R;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class FragmentDemographicsQuestionnaire extends SherlockFragment  {
	
    private Utils utilsHelper = null;
    private Cursor structureCursor = null;
    private int structureID;
	public Context mContext;
	
	private TextView TextView_CreatedOn = null;
	private TextView TextView_RecordID = null;    
	private EditText EditText_SurveyorName= null;
	private EditText EditText_Entry_Descriptor = null;
	private EditText EditText_Location = null;
	private EditText EditText_FunctionUsageNote = null;
	private EditText EditText_TenantAddress = null;
	private EditText EditText_TenantName= null;
	private EditText EditText_TenantPhoneNumber = null;
	private EditText EditText_OwnershipNote = null;
	private EditText EditText_YearBuilt = null;
	private EditText EditText_ConstructionTime = null;
	private EditText EditText_BulderNote = null;
	private EditText EditText_NumberOfAdults = null;
	private EditText EditText_NumberOfChildren = null;
	
	private CheckBox CheckBox_FunctionUsage_Residence = null;
	private CheckBox CheckBox_FunctionUsage_Mixed = null;
	private CheckBox CheckBox_FunctionUsage_Single = null;
	private CheckBox CheckBox_FunctionUsage_Multiple = null;
	private CheckBox CheckBox_FunctionUsage_Other = null;
	
	private Spinner Spinner_Ownership = null;
	private Spinner Spinner_Builder = null;

    private static final int OWNERSHIP_ADAPTOR_ID = 0;
    private static final int BUILDER_ADAPTOR_ID = 1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);      	
        
        utilsHelper = new Utils(getActivity().getApplicationContext());      

    } // end of the onCreate method
    
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    	
    	// Sets the cursor
        setStructureCursor(); 
    	
    	View fragmentView = inflater.inflate(R.layout.demographics_questionnaire_layout, container, false);    	
    	manageFormFields(fragmentView);
    	
    	return fragmentView;
    }
    
    private void setStructureCursor(){
        utilsHelper.openDatabase(); 
   	   // Get structure ID
          structureID = getActivity().getIntent().getIntExtra("structureID", -1); //Get structureID otherwise -1      
          structureCursor = utilsHelper.getStructureCursor(structureID); 
       utilsHelper.closeDatabase(); 
      }
   
    private void manageFormFields(View v){
    		
    	// Declares the text input fields
        TextView_CreatedOn = (TextView) v.findViewById(R.id.Dem_plainText_DateTime);     
        TextView_RecordID = (TextView) v.findViewById(R.id.Dem_plainText_RecordID);
        EditText_SurveyorName = (EditText) v.findViewById(R.id.Dem_editText_SurveyorName);
        EditText_Entry_Descriptor = (EditText) v.findViewById(R.id.Dem_editText_EntryDescriptor);
    	EditText_Location = (EditText) v.findViewById(R.id.Dem_editText_Location);
    	EditText_FunctionUsageNote = (EditText) v.findViewById(R.id.Dem_editText_FunctionUsageNote);
    	EditText_TenantAddress = (EditText) v.findViewById(R.id.Dem_editText_TenantAddress);
    	EditText_TenantName = (EditText) v.findViewById(R.id.Dem_editText_TenantName);
    	EditText_TenantPhoneNumber = (EditText) v.findViewById(R.id.Dem_editText_TenantPhoneNumber);
    	EditText_OwnershipNote = (EditText) v.findViewById(R.id.Dem_editText_OwnershipNote);
    	EditText_YearBuilt = (EditText) v.findViewById(R.id.Dem_editText_YearBuilt);
    	EditText_ConstructionTime = (EditText) v.findViewById(R.id.Dem_editText_ConstructionTime);
    	EditText_BulderNote = (EditText) v.findViewById(R.id.Dem_editText_BuilderNote);
    	EditText_NumberOfAdults = (EditText) v.findViewById(R.id.Dem_editText_NumberOfAdults);
    	EditText_NumberOfChildren = (EditText) v.findViewById(R.id.Dem_editText_NumberOfChildren);
    	
	    // Declares the checkbox input fields
    	CheckBox_FunctionUsage_Residence = (CheckBox) v.findViewById(R.id.Dem_checkBox_FunctionUsageResidence);
    	CheckBox_FunctionUsage_Mixed = (CheckBox) v.findViewById(R.id.Dem_checkBox_FunctionUsageMixed);
    	CheckBox_FunctionUsage_Single = (CheckBox) v.findViewById(R.id.Dem_checkBox_FunctionUsageSingle);
    	CheckBox_FunctionUsage_Multiple = (CheckBox) v.findViewById(R.id.Dem_checkBox_FunctionUsageMultiple);
    	CheckBox_FunctionUsage_Other= (CheckBox) v.findViewById(R.id.Dem_checkBox_FunctionUsageOther);

        // Sets the data to what exists in the database. It may be possible that this is nothing.
        String createdOn = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_CREATED_ON_DATETIME));
		String recordID = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_RECORD_ID));
		String surveyorName = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_SURVEYOR_NAME));
		String entryDescriptor = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_ENTRY_DESCRIPTOR));
		String location = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_LOCATION));
		String functionUsageNote = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_FUNCTION_USAGE_NOTE));
		String tenantAddress = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_TENANT_ADDRESS));
		String tenantName = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_TENANT_NAME));
		String tenantPhoneNumber = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_TENANT_PHONE_NUMBER));
		String ownershipNote = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_OWNERSHIP_STATUS_NOTE));
		String yearbuilt = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_YEAR_BUILT));
		String constructionTime = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_CONSTRUCTION_DURATION));
		String builderNote= structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_BUILDER_NOTE));
		String numberOfAdults = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NUMBER_OF_ADULTS));
		String numberOfChildren = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NUMBER_OF_CHILDREN));
		
		// Checks if data already exists for Check Box
		Boolean functionUsageResidence = stringToBool(structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_FUNCTION_USAGE_RESIDENCE)));
		Boolean functionUsageMixed= stringToBool(structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_FUNCTION_USAGE_MIXED)));
		Boolean functionUsageSingle= stringToBool(structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_FUNCTION_USAGE_SINGLE)));
		Boolean functionUsageMultiple= stringToBool(structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_FUNCTION_USAGE_MULTIPLE)));
		Boolean functionUsageOther= stringToBool(structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_FUNCTION_USAGE_OTHER)));
	     
//		// Sets the text of the input fields
		TextView_CreatedOn.setText(createdOn);
		TextView_RecordID.setText(recordID);
        EditText_SurveyorName.setText(surveyorName);
        EditText_Entry_Descriptor.setText(entryDescriptor);
    	EditText_Location.setText(location);
    	EditText_FunctionUsageNote.setText(functionUsageNote);
    	EditText_TenantAddress.setText(tenantAddress);
    	EditText_TenantName.setText(tenantName);
    	EditText_TenantPhoneNumber.setText(tenantPhoneNumber);
    	EditText_OwnershipNote.setText(ownershipNote);
    	EditText_YearBuilt.setText(yearbuilt);
    	EditText_ConstructionTime.setText(constructionTime);
    	EditText_BulderNote.setText(builderNote);
    	EditText_NumberOfAdults.setText(numberOfAdults);
    	EditText_NumberOfChildren.setText(numberOfChildren);
    	
    	// Sets the value of the Check Boxes
    	CheckBox_FunctionUsage_Residence.setChecked(functionUsageResidence);
    	CheckBox_FunctionUsage_Mixed.setChecked(functionUsageMixed);
    	CheckBox_FunctionUsage_Single.setChecked(functionUsageSingle);
    	CheckBox_FunctionUsage_Multiple.setChecked(functionUsageMultiple);
    	CheckBox_FunctionUsage_Other.setChecked(functionUsageOther);
		
        // Initializes view spinners
        initializeSpinners(v);
    }   
    
 public static boolean stringToBool(String s) {
  	  if (s == null || s.equals(""))
  	    return false;
  	  else if (s.equals("0"))
  	    return false;
  	  else if (s.equals("1"))
  		return true;
  	  throw new IllegalArgumentException(s+" is not a bool. Only 1 and 0 are.");
  }
    
 private void initializeSpinners(View v){
    	
// Ownership Array Adapter ========================================================================================================================
        ArrayAdapter<CharSequence> adapter_Ownership = ArrayAdapter.createFromResource(
        		getActivity().getApplicationContext(), R.array.Ownership, android.R.layout.simple_spinner_item );
        		adapter_Ownership.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);

        		Spinner_Ownership = (Spinner) v.findViewById(R.id.Dem_spinner_Ownership);
        		Spinner_Ownership.setAdapter( adapter_Ownership );
      			
      		//  Sets the location of spinner to saved value if there is one\
      			int ownershipPosition = getArrayPosition(OWNERSHIP_ADAPTOR_ID);
      			Spinner_Ownership.setSelection(ownershipPosition, true);  
      			
// Builder Array Adapter ========================================================================================================================
	    ArrayAdapter<CharSequence> adapter_Builder = ArrayAdapter.createFromResource(
	    		getActivity().getApplicationContext(), R.array.Builder, android.R.layout.simple_spinner_item );
	    		adapter_Builder.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);
	
	    		Spinner_Builder = (Spinner) v.findViewById(R.id.Dem_spinner_Builder);
	    		Spinner_Builder.setAdapter( adapter_Builder );
	  			
	  		//  Sets the location of spinner to saved value if there is one\
	  			int builderPosition = getArrayPosition(BUILDER_ADAPTOR_ID);
	  			Spinner_Builder.setSelection(builderPosition , true); 
      			      			  	
    }
 
 private int getArrayPosition(int spinnerType){
		
		int position=0;
		
		switch (spinnerType){
		
			case OWNERSHIP_ADAPTOR_ID:
				
				ArrayAdapter ownership_Adapter = (ArrayAdapter) Spinner_Ownership.getAdapter();			
	 			String ownershipValue= structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_OWNERSHIP_STATUS));
	 			position = ownership_Adapter.getPosition(ownershipValue);
				
				break;	
				
			case BUILDER_ADAPTOR_ID:
	
				ArrayAdapter builder_Adapter = (ArrayAdapter) Spinner_Builder.getAdapter();			
				String builderValue= structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_BUILDER));
				position = builder_Adapter.getPosition(builderValue);
	
				break;	
				
			default:				
				break;
			 		 		 		
		}							
		
		return position;
	}
   
} 